<template>
  <div class="scenic-edit-container">
    <el-card class="scenic-card">
      <div class="scenic-title">
        <span>{{ isEdit ? '编辑景区信息' : '添加新景区' }}</span>
      </div>
      <el-row :gutter="32" class="form-row">
        <el-col :span="12">
          <el-form :model="scenicForm" :rules="rules" ref="scenicForm" label-width="120px">
            <el-form-item label="景区名称" prop="scenicAreaName">
              <el-input v-model="scenicForm.scenicAreaName" />
            </el-form-item>
            <el-form-item label="景点级别" prop="scenicSpotLevel">
              <el-input v-model="scenicForm.scenicSpotLevel" />
            </el-form-item>
            <el-form-item label="海拔高度" prop="altitude">
              <el-input-number v-model="scenicForm.altitude" :min="0" />
            </el-form-item>
            <el-form-item label="综合难度" prop="comprehensiveDifficultyIndex">
              <el-rate v-model="scenicForm.comprehensiveDifficultyIndex" show-score text-color="#ff9900" score-template="{value}分" />
            </el-form-item>
            <el-form-item label="景点介绍" prop="scenicSpotDescription">
              <el-input v-model="scenicForm.scenicSpotDescription" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" />
            </el-form-item>
            <el-form-item label="省份" prop="province">
              <el-select v-model="scenicForm.province" filterable placeholder="请选择省份" @change="handleProvinceChange">
                <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="城市" prop="city">
              <el-select v-model="scenicForm.city" filterable placeholder="请选择城市">
                <el-option v-for="item in cityOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="scenicForm.detailAddress" />
            </el-form-item>
            <el-form-item label="更新时间" v-if="isEdit">
              <el-date-picker v-model="scenicForm.updateTime" type="datetime" disabled placeholder="选择日期时间" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" class="image-col">
          <div class="image-section">
            <span class="image-label">景区图片：</span>

            <!-- 修改后的九宫格，用于显示上传的图片 -->
            <div class="image-grid">
              <div v-for="(img, index) in scenicImages" :key="index" class="grid-item">
                <el-image :src="img" :preview-src-list="[img]" fit="cover" class="grid-image" />
                <div class="grid-item-actions">
                  <el-button type="danger" size="mini" @click="handleDeleteImage(img)">删除</el-button>
                  <el-upload action="http://localhost:8080/api/updateScenicImage" :show-file-list="false"
                    :on-success="loadScenicImages" :before-upload="beforeUpload"
                    :data="{ scenicSpotId: scenicForm.scenicSpotId, oldImageUrl: img }">
                    <el-button size="mini">修改</el-button>
                  </el-upload>
                </div>
              </div>

              <!-- 空白占位符，用Plus图标代替"位置i"文字 -->
              <div v-for="i in 9 - scenicImages.length" :key="'empty-' + i" class="grid-item empty-placeholder">
                <el-upload class="plus-upload" action="http://localhost:8080/api/uploadScenicImage" :show-file-list="false"
                  :on-success="handleUploadSuccess" :before-upload="beforeUpload"
                  :data="{ scenicSpotId: scenicForm.scenicSpotId || 0 }">
                  <el-icon class="placeholder-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="button-group">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { Upload, Plus } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  components: { Upload, Plus },
  data() {
    return {
      isEdit: false,
      scenicForm: {
        scenicSpotId: null,
        scenicAreaName: '',
        scenicSpotLevel: '',
        altitude: 0,
        comprehensiveDifficultyIndex: 0,
        scenicSpotDescription: '',
        province: '',
        city: '',
        detailAddress: '',
        updateTime: ''
      },
      rules: {
        scenicSpotId: [{ required: true, message: '请输入景区ID', trigger: 'blur' }],
        scenicAreaName: [{ required: true, message: '请输入景区名称', trigger: 'blur' }],
        scenicSpotLevel: [{ required: true, message: '请输入景点级别', trigger: 'blur' }],
        altitude: [{ required: true, message: '请输入海拔', trigger: 'blur' }],
        comprehensiveDifficultyIndex: [{ required: true, message: '请输入综合难度', trigger: 'blur' }],
        province: [{ required: true, message: '请选择省份', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
      },
      provinceOptions: [],
      cityOptions: [],
      regionOptions: [],
      regionMap: {},
      scenicImages: [],
      canUploadImage: false
    }
  },
  created() {
    const id = this.$route.query.id
    if (id) {
      this.isEdit = true
      this.loadScenicData(id)
      this.loadScenicImages(id)
      this.canUploadImage = true
    } else {
      this.generateScenicId()
    }
    this.loadRegionOptions()
  },
  methods: {
    generateScenicId() {
      axios.get('http://localhost:8080/mw/ScenicSpotList').then(res => {
        const spots = res.data || []
        const maxId = spots.length > 0 ? Math.max(...spots.map(s => s.scenicSpotId)) : 0
        this.scenicForm.scenicSpotId = maxId + 1
      })
    },
    loadRegionOptions() {
      axios.get('http://localhost:8080/api/regions').then(res => {
        this.regionOptions = res.data || []
        this.provinceOptions = [...new Set(this.regionOptions.map(r => r.province))]
        this.regionMap = {}
        this.regionOptions.forEach(r => {
          if (!this.regionMap[r.province]) this.regionMap[r.province] = []
          this.regionMap[r.province].push(r.city)
        })
      })
    },
    handleProvinceChange(val) {
      this.cityOptions = this.regionMap[val] || []
      if (!this.cityOptions.includes(this.scenicForm.city)) {
        this.scenicForm.city = ''
      }
    },
    loadScenicData(id) {
      axios.get(`http://localhost:8080/mw/ScenicSpotById?id=${id}`).then(res => {
        const data = res.data
        this.scenicForm = {
          scenicSpotId: data.scenicSpotId,
          scenicAreaName: data.scenicAreaName,
          scenicSpotLevel: data.scenicSpotLevel,
          altitude: data.altitude,
          comprehensiveDifficultyIndex: data.comprehensiveDifficultyIndex,
          scenicSpotDescription: data.scenicSpotDescription,
          province: '',
          city: '',
          detailAddress: data.detailAddress,
          updateTime: data.updateTime
        }
        // 根据 regionId 查找省份和城市
        axios.get('http://localhost:8080/api/regions').then(regionRes => {
          const regionList = regionRes.data
          const region = regionList.find(item => item.regionID === data.regionId)
          this.scenicForm.province = region ? region.province : ''
          this.scenicForm.city = region ? region.city : ''
          this.handleProvinceChange(this.scenicForm.province)
        })
      })
    },
    loadScenicImages(scenicSpotId) {
      const id = scenicSpotId || this.scenicForm.scenicSpotId
      if (!id) return
      axios.get(`http://localhost:8080/api/scenicSpotImage?scenicSpotId=${id}`).then(res => {
        this.scenicImages = res.data || []
      })
    },
    beforeUpload(file) {
      if (!this.canUploadImage) {
        this.$message.error('请先添加景区信息保存后再上传')
        return false
      }
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) {
        this.$message.error('只能上传图片文件！')
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB！')
      }
      return isImage && isLt5M
    },
    // 修改上传成功处理函数
    handleUploadSuccess(response) {
      if (response.success) {
        this.$message.success('图片上传成功')
        this.loadScenicImages()  // 刷新已上传的图片
      } else {
        this.$message.error(response.msg || '图片上传失败')
      }
    },
    handleDeleteImage(imageUrl) {
      axios.delete('http://localhost:8080/api/scenicSpotImage', {
        params: {
          scenicSpotId: this.scenicForm.scenicSpotId,
          imageUrl
        }
      }).then(res => {
        if (res.data.success) {
          this.$message.success('图片删除成功')
          this.loadScenicImages()
        } else {
          this.$message.error(res.data.msg || '图片删除失败')
        }
      })
    },
    submitForm() {
      this.$refs.scenicForm.validate(valid => {
        if (valid) {
          // 查找 regionId
          const region = this.regionOptions.find(
            r => r.province === this.scenicForm.province && r.city === this.scenicForm.city
          )
          if (!region) {
            this.$message.error('请选择有效的省份和城市')
            return
          }
          const submitData = {
            scenicSpotId: this.scenicForm.scenicSpotId,
            scenicAreaName: this.scenicForm.scenicAreaName,
            scenicSpotLevel: this.scenicForm.scenicSpotLevel,
            altitude: this.scenicForm.altitude,
            comprehensiveDifficultyIndex: this.scenicForm.comprehensiveDifficultyIndex,
            scenicSpotDescription: this.scenicForm.scenicSpotDescription,
            regionId: region.regionID,
            detailAddress: this.scenicForm.detailAddress,
            updateTime: this.scenicForm.updateTime
          }
        const url = this.isEdit
          ? 'http://localhost:8080/mw/updateScenicSpot'
          : 'http://localhost:8080/mw/addScenicSpot'
        const method = this.isEdit ? 'put' : 'post'
        axios({
          method,
          url,
          data: submitData
        })
        .then(() => {
          this.$message.success(this.isEdit ? '修改成功' : '添加成功')
          this.isEdit = true
          this.canUploadImage = true
          this.loadScenicImages(this.scenicForm.scenicSpotId)
        })
        .catch(() => {
          this.$message.error(this.isEdit ? '修改失败' : '添加失败')
        })
                }
              })
    },
    goBack() {
      this.$router.push('/scenic/list')
    }
  }
}
</script>

<style scoped>
.scenic-edit-container {
  padding: 32px;
  background: #f7f8fa;
  min-height: 100vh;
}

.scenic-card {
  max-width: 1100px;
  width: 100%;
  margin: 0 auto;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 4px 24px #e6e6e6;
}

.scenic-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 24px;
  color: #333;
  text-align: center;
}

.form-row {
  margin-bottom: 24px;
}

.image-col {
  display: flex;
  flex-direction: column;
}

.image-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-label {
  display: block;
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  width: 100%;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /* 3列 */
  grid-gap: 16px;
  /* 网格间距 */
  margin-top: 20px;
  /* 与上方表单的间距 */
  width: 100%;
}

.grid-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 10px;
  min-height: 150px;
  /* 最小高度 */
  cursor: pointer;
  transition: all 0.3s;
  border: 1px dashed #dcdfe6;
}

.grid-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 8px;
}

.grid-item-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.empty-placeholder {
  border-style: dashed;
  background-color: #fafafa;
}

.placeholder-icon {
  font-size: 24px;
  color: #909399;
  margin-bottom: 8px;
  cursor: pointer; /* 添加指针样式，表明可点击 */
}

/* 为Plus上传组件添加样式 */
.plus-upload {
  display: contents; /* 让子元素直接成为网格项的子元素 */
}

/* 保留原有的上传成功处理样式 */
.image-placeholder {
  width: 100%;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #c0c4cc;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
}
</style>